package com.pic.mgt.action;

import java.util.Calendar;
import java.util.Collections;

import com.pic.mgt.log.IgxLog;
import com.pic.mgt.scheduler.Scheduler;
import com.pic.mgt.scheduler.SchedulerException;

public class ScheduleAutoInspectMissUnitActionImpl implements
		ScheduleAutoInspectMissUnitAction {
	
	private Scheduler scheduler;
	
	private long autoRecoveryLoseCheckThreshHold_DL;
	private long autoRecoveryLoseCheckThreshHold_UL;

	@Override
	public synchronized boolean scheduleAutoInspectMissUnitAndRecover() {
		try {
			// 不管排程內是否已有該JOB或沒有,先做移除的動作
			this.scheduler.removeJob(autoInspectMissUnitJobName, autoInspectMissUnitJobGroupName);
			
			// 再將排程加入
			
			// 計算執行時間
			int autoRecoveryLoseCheckThreshHold;
			if (autoRecoveryLoseCheckThreshHold_DL > autoRecoveryLoseCheckThreshHold_UL) {
				autoRecoveryLoseCheckThreshHold = (int)(autoRecoveryLoseCheckThreshHold_DL / 1000);
			}
			else if (autoRecoveryLoseCheckThreshHold_DL < autoRecoveryLoseCheckThreshHold_UL) {
				autoRecoveryLoseCheckThreshHold = (int)(autoRecoveryLoseCheckThreshHold_UL / 1000);
			}
			else {
				autoRecoveryLoseCheckThreshHold = (int)(autoRecoveryLoseCheckThreshHold_UL / 1000);
			}
			Calendar executionTime = Calendar.getInstance();
			executionTime.add(Calendar.SECOND, autoRecoveryLoseCheckThreshHold + 5);
			
			// 加入排程
			this.scheduler.scheduleSimpleJob(
					executionTime.getTime(),
					autoInspectMissUnitJobName,
					autoInspectMissUnitJobGroupName,
					AutoInspectMissUnitActionImplQuartzJobBean.class,
					Collections.EMPTY_MAP);
			
			// ********************** Log **********************
			IgxLog.messageLog.info(this,
							"Auto-inspection miss unit process is going to perform at '{}'",
							executionTime.getTime());
			// ********************** Log **********************
			
			return true;
		} catch (SchedulerException e) {
			// ********************** Log **********************
			IgxLog.messageLog.error(this,
					"SUDA-332 Adding auto-inspection miss unit process schedule failed.");
			// ********************** Log **********************
			
			return false; 
		}
	}
	
	// --- getter and setter ---

	public void setAutoRecoveryLoseCheckThreshHold_DL(
			long autoRecoveryLoseCheckThreshHoldDL) {
		autoRecoveryLoseCheckThreshHold_DL = autoRecoveryLoseCheckThreshHoldDL;
	}

	public void setAutoRecoveryLoseCheckThreshHold_UL(
			long autoRecoveryLoseCheckThreshHoldUL) {
		autoRecoveryLoseCheckThreshHold_UL = autoRecoveryLoseCheckThreshHoldUL;
	}

	public void setScheduler(Scheduler scheduler) {
		this.scheduler = scheduler;
	}

}
